<template>
    <van-sticky>
        <van-nav-bar :left-text="!store.offlineMode ? '注销' : ''" :left-arrow="!store.offlineMode"
            @click-left="onClickLeft">
            <template #title>
                <span>{{ store.user.name }}</span>
            </template>
            <template #right>
                <div class="network-status-container">
                    <span :class="['mode-span', store.offlineMode ? 'offline-active' : 'online-active']"
                        @click="toggleOfflineMode">
                        {{ store.offlineMode ? '离线模式' : '在线模式' }}
                    </span>
                    <div class="network-indicator" :class="{
                        'unknown': isOnline === null,
                        'online': isOnline === true,
                        'offline': isOnline === false,
                        'detecting': isDetecting
                    }"></div>
                </div>
            </template>
        </van-nav-bar>
    </van-sticky>

    <div v-if="store.offlineMode" style="margin-top: 0.5rem;">
        <div v-if="hasZxlzData" style="margin-bottom: 16px;">
            <span class="title-grid">专项流转</span>
            <van-cell-group v-for="(item, index) in zxlzDataList" :key="index">
                <van-cell :title="item.detail.locationName + ' / ' + item.detail.zxPlanName"
                    :label="formatDate(item.detail.date, 4) + ' / ' + item.detail.personnelInfo" clickable
                    @click="store.setOfflineMode(true); router.push('/ZhuangXiang/RenWu/detail?id=' + item.id)">
                    <template #value>
                        <van-tag :color="getStatusColor(item.detail.status)">{{ item.detail.status }}</van-tag>
                    </template>
                </van-cell>
            </van-cell-group>
        </div>
        <div v-if="hasBjclData" style="margin-bottom: 16px;">
            <span class="title-grid">表计抄录</span>
            <van-cell-group v-for="(item, index) in bjclDataList" :key="index">
                <van-cell :title="item.key.replace('-', ' / ')" :label="new Date(item.data.date).toLocaleString()"
                    :value="calculateCompletionRate(item.data.list)"
                    :class="{ 'complete-green': isAllCompleted(item.data.list), 'complete-red': !isAllCompleted(item.data.list) }"
                    clickable
                    @click="store.setOfflineMode(true); router.push('/BiaoJi/ChaoLu?title=' + encodeURIComponent(item.key.replace('-', ' / ')))" />
            </van-cell-group>
        </div>
        <div v-if="!hasZxlzData && !hasBjclData" class="empty-tip">
            暂无离线缓存数据
            <div v-if="!isOnline" class="network-warning">当前处于离线状态</div>
        </div>
    </div>
    <template v-else-if="!store.offlineMode">
        <div class="title-grid">应用</div>
        <van-grid class="grid" :gutter="1" clickable>
            <van-grid-item class="icon-color" v-for="appData in appDataList[0]" :key="appData.id" :id="appData.id"
                :icon="appData.icon" :text="appData.text" :state="appData.state" v-show="appData.limit == '1'"
                :class="{ disabled: appData.state == 0 }" @click="appClick($event, '应用')" />
        </van-grid>
        <div class="title-grid">巡视表单（得帆云）</div>
        <van-grid class="grid" :gutter="1" clickable>
            <van-grid-item class="icon-color" v-for="appData in appDataList[1]" :key="appData.id" :id="appData.id"
                :icon="appData.icon" :text="appData.text" :url="appData.url" :state="appData.state"
                v-show="appData.limit == '1'" :class="{ disabled: appData.state == 0 }"
                @click="appClick($event, '巡视表单')" />
        </van-grid>
        <div class="title-row">
            <van-row>
                <van-col span="16" class="todo-tab-container">
                    <span class="todo-tab" :class="{ active: currentTab === 'todo' }" @click="switchTab('todo')">
                        待办
                    </span>
                    <span class="tab-separator">/</span>
                    <span class="todo-tab" :class="{ active: currentTab === 'done' }" @click="switchTab('done')">
                        已办
                    </span>
                </van-col>
                <van-col span="8" class="daiban-count"> {{ daibanList.length }}条 </van-col>
            </van-row>
        </div>
        <div class="daiban-container">
            <van-skeleton title :row="2" :loading="isLoading" v-if="isLoading" v-for="i in 4" />
            <template v-else>
                <van-cell-group inset v-for="daiban in daibanList" :key="daiban.id" class="daiban-cell-group">
                    <van-cell clickable @click="todoClick(daiban)" :title="daiban.title"
                        :value="formatRelativeTime(daiban.updatedAt)" :label="daiban.content" class="daiban-cell" />
                </van-cell-group>
                <div v-if="daibanList.length === 0" class="empty-tip">
                    {{ currentTab === 'todo' ? '暂无待办事项' : '暂无已办事项' }}
                </div>
            </template>
        </div>
    </template>
</template>

<script setup>
import { computed, onMounted, ref, watch, onUnmounted } from 'vue';
import { useRouter } from "vue-router";
import useStore from "@/store/index";
import { useCookies } from "vue3-cookies";
import { appDataList } from '@/data/homeConfig';
import { showConfirmDialog } from 'vant';
import todoAPI from "@/api/todo.js";
import zxlzAPI from "@/api/zxlz.js";
import { errorNotify, clearAllCaches, getStatusColor, pingServer } from "@/utils/Misc";
import { formatDate } from "@/utils/Format";
import db from '@/utils/Dexie';

const router = useRouter();
const store = useStore();
const { cookies } = useCookies();

// 自定义网络状态检测
const isOnline = ref(null); // 初始化为null表示未知状态
const isDetecting = ref(false); // 用于指示是否正在检测网络
let pingInterval = null;

// 执行网络ping检测
const performPing = async () => {
    isDetecting.value = true;
    try {
        const result = await pingServer();
        isOnline.value = result;
    } finally {
        setTimeout(() => {
            isDetecting.value = false;
        }, 300);
    }
};

const daibanList = ref([]);
const isLoading = ref(true);
const currentTab = ref('todo');
const zxlzDataList = ref([]);
const bjclDataList = ref([]);
const hasZxlzData = ref(false);
const hasBjclData = ref(false);

onMounted(async () => {
    if (store.offlineMode) {
        await checkOfflineData();
    } else {
        fetchTodoList();
    }

    // 立即执行第一次网络检测
    await performPing();

    // 设置每30秒执行一次ping检测
    pingInterval = setInterval(async () => {
        await performPing();
    }, 30000); // 30秒
});

// 监听网络状态变化
watch(isOnline, async (newStatus, oldStatus) => {
    if (newStatus === false && oldStatus === true) {
        // 网络从联网变为断网时，自动切换为离线模式
        await checkOfflineData();
        store.setOfflineMode(true);
    } else if (newStatus) {
        // 网络恢复时的处理
    }
});

// 组件卸载时移除事件监听和清除定时器
onUnmounted(() => {
    if (pingInterval) {
        clearInterval(pingInterval);
    }

});

const calculateCompletionRate = (list) => {
    if (!list || !Array.isArray(list)) return '0 / 0';
    const totalCount = list.length;
    const completedCount = list.filter(item => {
        return item && item.value && item.value.trim() !== '' && item.images && Array.isArray(item.images) && item.images.length > 0;
    }).length;
    return `${completedCount} / ${totalCount}`;
};

const isAllCompleted = (list) => {
    if (!list || !Array.isArray(list) || list.length === 0) return false;
    return list.every(item => {
        return item && item.value && item.value.trim() !== '' && item.images && Array.isArray(item.images) && item.images.length > 0;
    });
};

const onClickLeft = () => {
    showConfirmDialog({
        title: '注销',
        message: '确定要注销吗？登录其他账号将会清空缓存数据。',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnPopstate: false
    }).then(() => {
        cookies.remove("token");
        router.push('/');
    }).catch(() => { });
};

const switchTab = (tab) => {
    if (currentTab.value !== tab) {
        currentTab.value = tab;
        fetchTodoList();
    }
};

const fetchTodoList = async () => {
    // 直接加载待办数据，不等待网络检测结果
    isLoading.value = true;
    const formData = {
        sign: null,
        userId: store.user.id,
        isDeal: currentTab.value === 'done'
    };
    if (currentTab.value === 'done') {
        formData.page = {
            pageNo: 1,
            pageSize: 10
        };
    }
    try {
        const res = await todoAPI.list(formData);
        const sortedList = res.data.page.list.sort((a, b) => {
            return new Date(b.updatedAt) - new Date(a.updatedAt);
        });
        daibanList.value = sortedList;
        isLoading.value = false;
    } catch (error) {
        errorNotify('Home.vue', 'fetchTodoList', error);
        isLoading.value = false;
    }
};

const formatRelativeTime = (timeString) => {
    if (!timeString) return '';
    const updateTime = new Date(timeString);
    const now = new Date();
    const diffMs = now - updateTime;
    const diffSec = Math.floor(diffMs / 1000);
    if (diffSec < 60) {
        return '刚刚';
    }
    const diffMin = Math.floor(diffSec / 60);
    if (diffMin < 60) {
        return `${diffMin}分钟前`;
    }
    const diffHour = Math.floor(diffMin / 60);
    if (diffHour < 24) {
        return `${diffHour}小时前`;
    }
    const diffDay = Math.floor(diffHour / 24);
    return `${diffDay}天前`;
};

const appClick = (event, type) => {
    const state = event.currentTarget.getAttribute("state");
    if (state !== "1") {
        return;
    }
    if (type == "应用") {
        const url = "/" + event.currentTarget.id;
        router.push({ path: url });
    } else if (type == "巡视表单") {

    }
};

const todoClick = async (daiban) => {
    let path;
    switch (daiban.sign) {
        case 2:
        case 3:
        case 8:
            path = "/ZhuangXiang/RenWu/detail";
            break;
        case 7:
            path = "/ZhuangXiang/RenWu/list";
            zxlzAPI.todoApproval(daiban.parameter);
            break;
        case 9:
            path = "/BiaoJi/HeYan";
            break;
        default:
            path = "/ZhuangXiang/detail";
    }
    router.push({
        path: path,
        query: {
            id: daiban.parameter,
        }
    });
};

const checkOfflineData = async () => {
    try {
        const zxlzData = await db.zxlzCache.toArray();
        const filteredZxlzData = zxlzData.filter(item => {
            return item.data !== undefined && item.detail && item.detail.status === '进行中';
        }).map(item => {
            if (item.detail && (item.detail.leaderName || item.detail.memberNames)) {
                const leaderName = item.detail.leaderName || '';
                const memberNames = item.detail.memberNames ? item.detail.memberNames.replace(/,/g, '、') : '';
                item.detail.personnelInfo = leaderName + (leaderName && memberNames ? '、' : '') + memberNames;
            }
            return item;
        });
        zxlzDataList.value = filteredZxlzData;
        hasZxlzData.value = filteredZxlzData.length > 0;

        const bjclData = await db.bjclCache.toArray();
        const filteredBjclData = bjclData.filter(item => {
            return item.data && item.data.list && item.data.list.length > 0;
        });
        bjclDataList.value = filteredBjclData;
        hasBjclData.value = filteredBjclData.length > 0;
    } catch (error) {
        console.error("获取离线数据失败:", error);
    }
};

const toggleOfflineMode = async () => {
    if (store.offlineMode) {
        showConfirmDialog({
            title: '退出离线模式',
            message: "请确认已在有网状态完成相关项目的提交。",
            confirmButtonText: '确定退出',
            closeOnPopstate: false
        }).then(async () => {
            // 先切换模式
            store.setOfflineMode(false);
            fetchTodoList();
            // 再执行ping检查
            await performPing();
        }).catch(() => { });
    } else {
        showConfirmDialog({
            title: '启用离线模式',
            message: "请在进入无网络区域前确保已缓存需要的数据。",
            confirmButtonText: '确认启用',
            closeOnPopstate: false
        }).then(async () => {
            await checkOfflineData();
            // 先切换模式
            store.setOfflineMode(true);
            // 再执行ping检查
            await performPing();
        }).catch(() => { });
    }
};
</script>

<style scoped>
/* 全局样式优化 */
:deep(.van-cell__label) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
}

:deep(.van-cell__value) {
    flex: 1;
}

:deep(.van-cell__title) {
    flex: 4;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 导航栏样式增强 */
:deep(.van-nav-bar) {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

:deep(.van-nav-bar__left) {
    transition: transform 0.2s ease;
}

:deep(.van-nav-bar__left:active) {
    transform: scale(0.95);
}

:deep(.van-nav-bar__title) {
    font-weight: 600;
    font-size: 18px;
}

/* 模式切换按钮增强 */
.mode-span {
    font-size: 12px;
    font-weight: 600;
    padding: 4px 8px;
    border-radius: 12px;
    transition: all 0.3s ease;
    cursor: pointer;
}

.mode-span:active {
    transform: scale(0.95);
}

.online-active {
    color: #07C160;
    background-color: rgba(7, 193, 96, 0.1);
}

.offline-active {
    color: #fa8c16;
    background-color: rgba(250, 140, 22, 0.1);
}

/* 状态指示器增强 */
.network-status-container {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px;
    border-radius: 8px;
    transition: background-color 0.3s ease;
}

.network-status-container:active {
    background-color: rgba(0, 0, 0, 0.05);
}

.network-indicator {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    transition: all 0.3s ease;
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.6);
}

.network-indicator.unknown {
    background-color: #999;
}

.network-indicator.online {
    background-color: #07C160;
    box-shadow: 0 0 0 2px rgba(7, 193, 96, 0.3), 0 0 10px rgba(7, 193, 96, 0.5);
}

.network-indicator.offline {
    background-color: #FF6B6B;
    box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.3), 0 0 10px rgba(255, 107, 107, 0.5);
}

.network-indicator.detecting {
    animation: pulse 0.6s ease-in-out infinite;
}

@keyframes pulse {
    0%, 100% {
        opacity: 1;
        transform: scale(1);
    }
    50% {
        opacity: 0.4;
        transform: scale(1.1);
    }
}

/* 标题样式优化 */
.title-grid,
.title-row {
    font-weight: 600;
    padding: 1rem 0 0.5rem 0.75rem;
    color: #333;
    position: relative;
    margin-top: 0.5rem;
}

.title-grid::before,
.title-row::before {
    content: '';
    position: absolute;
    left: 0;
    top: 1rem;
    bottom: 0.5rem;
    width: 3px;
    background: linear-gradient(to bottom, #1989fa, #40a9ff);
    border-radius: 3px;
}

/* 网格布局增强 */
.grid {
    margin: 0 0.5rem 0.75rem 0.5rem;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 图标增强效果 */
.icon-color {
    color: #1989fa;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
}

.icon-color::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    border-radius: 50%;
    background-color: rgba(25, 137, 250, 0.1);
    transform: translate(-50%, -50%);
    transition: width 0.6s, height 0.6s;
}

.icon-color:active::after {
    width: 100%;
    height: 100%;
}

.icon-color:not(.disabled) {
    cursor: pointer;
}

.icon-color:not(.disabled):active {
    transform: scale(0.95);
}

.icon-color.disabled {
    opacity: 0.5;
    color: gray;
}

:deep(.icon-color .van-icon) {
    font-size: 36px;
    transition: transform 0.3s ease;
}

.icon-color:not(.disabled):hover :deep(.van-icon) {
    transform: scale(1.1);
}

/* 待办事项样式增强 */
.daiban-container {
    overflow-y: auto;
    max-height: calc(100vh - 320px);
    padding: 0 0.5rem;
}

.daiban-cell-group {
    border-radius: 12px !important;
    border: 1px solid #f0f0f0 !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    margin: 0 0 0.75rem 0 !important;
    transition: all 0.3s ease;
    overflow: hidden;
}

.daiban-cell-group:active {
    transform: translateY(2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.daiban-cell {
    display: flex;
    flex-direction: column;
    justify-content: center;
    transition: background-color 0.2s ease;
}

.daiban-cell:active {
    background-color: rgba(0, 0, 0, 0.03);
}

:deep(.van-cell-group) {
    border: 1px solid #f5f5f5;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
    margin: 0.75rem;
    transition: all 0.3s ease;
}

:deep(.van-cell-group):active {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 选项卡样式增强 */
.todo-tab-container {
    display: flex;
    align-items: center;
    gap: 8px;
}

.todo-tab {
    cursor: pointer;
    transition: all 0.3s ease;
    font-weight: 500;
    color: #666;
    padding: 4px 8px;
    border-radius: 4px;
    position: relative;
}

.todo-tab:hover {
    background-color: rgba(0, 0, 0, 0.03);
}

.todo-tab.active {
    color: #1989fa;
    font-size: 16px;
    font-weight: 600;
}

.todo-tab.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 3px;
    background-color: #1989fa;
    border-radius: 3px;
}

.tab-separator {
    color: #e0e0e0;
    font-size: 14px;
}

/* 待办数量样式 */
.daiban-count {
    text-align: right;
    padding-right: 0.75rem;
    color: #1989fa;
    font-weight: 600;
    font-size: 14px;
}

/* 骨架屏样式增强 */
:deep(.van-skeleton) {
    width: 100%;
    margin-bottom: 0.75rem;
    border: 1px solid #f5f5f5;
    padding: 1rem;
    border-radius: 12px;
    box-sizing: border-box;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    overflow: hidden;
}

/* 完成状态颜色 */
.complete-green :deep(.van-cell__value) {
    color: #07C160;
    font-weight: 600;
}

.complete-red :deep(.van-cell__value) {
    color: #EE0A24;
    font-weight: 600;
}

/* 空状态样式简化 */
.empty-tip {
    text-align: center;
    padding: 3rem 1rem;
    color: #999;
    font-size: 1rem;
}

/* 网络警告样式增强 */
.network-warning {
    margin-top: 12px;
    padding: 10px 16px;
    background-color: #fffbe6;
    border: 1px solid #ffe58f;
    border-radius: 8px;
    color: #fa8c16;
    font-size: 0.9rem;
    text-align: center;
    box-shadow: 0 2px 8px rgba(250, 140, 22, 0.1);
    transition: all 0.3s ease;
}

/* 离线模式内容样式 */
:deep(.van-cell) {
    transition: all 0.3s ease;
}

:deep(.van-cell:active) {
    background-color: rgba(0, 0, 0, 0.05);
}

/* 标签样式增强 */
:deep(.van-tag) {
    font-weight: 500;
    padding: 2px 8px;
    border-radius: 4px;
    transition: all 0.3s ease;
}

/* 滚动条样式优化 */
.daiban-container::-webkit-scrollbar {
    width: 4px;
}

.daiban-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.daiban-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.daiban-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 添加页面加载动画 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.daiban-container > *,
.grid,
.title-grid,
.title-row {
    animation: fadeIn 0.5s ease-out;
}

/* 延迟动画效果 */
.title-grid:nth-child(1),
.grid:nth-child(2) {
    animation-delay: 0.1s;
}

.title-grid:nth-child(3),
.grid:nth-child(4) {
    animation-delay: 0.2s;
}

.title-row {
    animation-delay: 0.3s;
}

.daiban-container {
    animation-delay: 0.4s;
}
</style>
